<template>
  <van-form @submit="onSubmit">
    <van-field v-model="form.name" name="name" label="姓名" :maxlength="8" placeholder="请输入姓名" :rules="[{ required: true, message: '请输入姓名' }]" />
    <van-field
      v-model="form.phone"
      name="phone"
      label="手机号"
      :maxlength="11"
      placeholder="请输入手机号"
      :rules="[
        { required: true, message: '请输入手机号' },
        { pattern: regexp.phone, message: '请输入正确手机号' }
      ]"
    />
    <van-field v-model="form.passWord" type="password" name="passWord" label="设置密码" placeholder="请输入密码" :rules="[{ required: true, message: '请输入密码' }]" />
    <van-field
      v-model="form.confirm"
      type="password"
      name="confirm"
      label="确认密码"
      placeholder="请输入确认密码"
      :rules="[
        { required: true, message: '请输入确认密码' },
        { validator, message: '两次输入密码不一致' }
      ]"
    />
    <div style="margin: 16px">
      <van-button round block type="info" native-type="submit">立即注册</van-button>
    </div>

    <div class="hl-goto-login">已有账号 <router-link :to="{ name: 'Login' }">去登录</router-link></div>
  </van-form>
</template>

<script>
import { Form } from 'vant'
import { Register } from '../../api/user'
import regexp from '../../utils/validate'
export default {
  components: {
    [Form.name]: Form
  },
  data() {
    return {
      regexp,
      form: { passWord: null }
    }
  },
  methods: {
    validator(val) {
      const { passWord } = this.form
      return passWord == val
    },
    onSubmit(values) {
      Register(values)
        .then(res => {
          if (res) {
            this.form = {}
            this.$toast('注册成功')
            setTimeout(() => {
              this.$router.push({ name: 'Login' })
            }, 1000)
          } else this.$toast('注册失败')
        })
        .catch(err => {
          this.$toast(err)
        })
    }
  }
}
</script>

<style lang="less">
.hl-goto-login {
  color: #646566;
  font-size: 14px;
  margin-right: 16px;
  float: right;
  a {
    color: #666;
  }
  &::after {
    content: '';
    display: table;
    clear: both;
  }
}
</style>
